package cn.kgc.tangcco.anyang.util.mybaits;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {

	// 实例化自身
	private static MyBatisUtil myBatisUtil = new MyBatisUtil();

	// 声明核心配置文件路径
	private static String resource = "mybatis-config.xml";
	// 加载核心配置文件到字符流中
	private static Reader reader;
	// 构建会话工场即获取数据源
	private static SqlSessionFactory sqlSessionFactory;
	static {
		try {
			reader = Resources.getResourceAsReader(resource);
			// 构建会话工场即获取数据源
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 防止外部实例化该类
	private MyBatisUtil() {
		super();
	}

	public SqlSession getSession() {
		// 从数据源获取连接
		return sqlSessionFactory.openSession();
	}

	public static MyBatisUtil build() {
		return myBatisUtil;
	}
}
